package com.yizhilu.os.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import com.yizhilu.os.core.service.cache.MemCache;
import com.yizhilu.os.edu.entity.kuaijidao.TemplateData;
import com.yizhilu.os.edu.entity.kuaijidao.WxTemplate;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WeChatUtil {


	public static String getCourseTempMsg(String toUser,Map<String,TemplateData> m) {
		
		  WxTemplate temp = new WxTemplate();
		  
	      temp.setUrl("http://weixin.qq.com/download");
	      temp.setTouser(toUser);
	      temp.setTopcolor("#000000");
	      temp.setTemplate_id("biTLzYp5bLibNA0vcL1axTPayjxggP3Ao55o_bFdN-I");	      
	      temp.setData(m);	     

	      return  JSONObject.fromObject(temp).toString();

	}
	
	
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			System.out.println("微信服务器连接超时！");
		} catch (Exception e) {
			System.out.println("HTTPS请求错误，错误信息：\n" + e.getMessage());
		}
		return jsonObject;
	}

	// 获取access_token的接口地址（GET） 限200（次/天）
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	/**
	 * 获取access_token
	 */
	public static AccessToken getAccessToken() {

		String appId = "wx3d1f8a4e695dfd27";
		String appSecret = "fc7bab243a53020749298b86f5074e38";

		AccessToken accessToken = null;

		MemCache memCache = MemCache.getInstance();
		
		boolean cleanToken =false;

		//尝试从memCache获得
		accessToken =(AccessToken)memCache.get("accessToken");
		
		
		
		if(accessToken!=null ){
			Long now=System.currentTimeMillis();
			Long getedTime=(now - accessToken.getGetTime())/1000 +100;
			if(getedTime> accessToken.getExpiresIn())
			{
				cleanToken=true;
			}
			System.out.print( accessToken.getExpiresIn()+"已获取时间:+++++++++"+getedTime);
			
		}
		
		

		if(accessToken==null || cleanToken ){
			String requestUrl = access_token_url.replace("APPID", appId).replace(
					"APPSECRET", appSecret);
			JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
			// 如果请求成功
			if (null != jsonObject) {
				try {
					accessToken = new AccessToken();
					accessToken.setToken(jsonObject.getString("access_token"));
					accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
					accessToken.setGetTime(System.currentTimeMillis());
				
					memCache.set("accessToken", accessToken);
					System.out.println("直接获得TOKEN成功"+jsonObject.getInt("expires_in"));
				} catch (JSONException e) {
					accessToken = null;
					// 获取token失败
					System.out.println("获取TOKEN失败("+jsonObject.getInt("errcode")+")："+WeChatErrorCode.ERRORCODE.get(jsonObject.getInt("errcode")));
				}
			}
		}
		return accessToken;
	}

	// 菜单创建（POST） 限100（次/天）

	public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	/**
	 * 创建菜单
	 * @param jsonMenu
	 * @param accessToken
	 * @return
	 */
	public static int createMenu(String jsonMenu, String accessToken) {
		int result = 0;

		// 拼装创建菜单的url
		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				System.out.println("创建菜单失败("+result+")："+WeChatErrorCode.ERRORCODE.get(result));
			}
		}
		return result;
	}
	
	public static String send_msg = "https://api.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";

	/**
	 * 发送消息
	 * @param jsonMsg
	 * @param accessToken
	 * @return
	 */
	public static int SendMsg(String jsonMsg, String accessToken) {
		int result = 0;
		// 拼装创建菜单的url
		String url = send_msg.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = httpRequest(url, "POST", jsonMsg);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				System.out.println("发送消息失败("+result+")："+WeChatErrorCode.ERRORCODE.get(result));
			}
		}
		return result;
	}
	
	// 获取access_token的接口地址（GET） 限200（次/天）
	public final static String access_token_web_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	/**
	 * 获取access_token
	 */
	public static String getAccessOpenId(String code) {

		String appId = "wx3d1f8a4e695dfd27";
		String appSecret = "fc7bab243a53020749298b86f5074e38";



	
		String requestUrl = access_token_web_url.replace("APPID", appId).replace(
				"CODE", code).replace("SECRET", appSecret);
		System.out.println("request++"+requestUrl);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				System.out.println("直接获得openid成功"+jsonObject.toString());
				return jsonObject.getString("openid");
				
				
			} catch (JSONException e) {
				e.printStackTrace();
				// 获取openid失败
				System.out.println("获取openid失败("+jsonObject.getInt("errcode")+")："+WeChatErrorCode.ERRORCODE.get(jsonObject.getInt("errcode")));
				return null;
				
			}
		}
		
		return null;
	}
	
	public static String send_tmp_msg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	
	/**
	 * 发送消息
	 * @param jsonMsg
	 * @param accessToken
	 * @return
	 */
	public static int SendTempMsg(String jsonMsg, String accessToken) {
		int result = 0;
		// 拼装创建菜单的url
		String url = send_tmp_msg.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = httpRequest(url, "POST", jsonMsg);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				System.out.println("发送消息失败("+result+")："+WeChatErrorCode.ERRORCODE.get(result));
			}
		}
		return result;
	}
	
	
	
}
